#!/bin/sh
# Depend on the rdesktop package
#
# Copyright 2007, Led <ledest@gmail.com>
# 
# This program is free software; you can redistribute it and/or modify it under
# the terms of the GNU General Public License as published by the Free Software
# Foundation; either version 2, or (at your option) any later version.
# 
# This program is distributed in the hope that it will be useful, but WITHOUT ANY
# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
# PARTICULAR PURPOSE.  See the GNU General Public License for more details.
# 
# You should have received a copy of the GNU General Public License with your
# Debian GNU system, in /usr/share/common-licenses/GPL.  If not, write to the
# Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
# 02111-1307, USA.

Message()
{
Result=2
while [ $Result -gt 1 ]; do
    #xmessage -buttons 'Repeate':0,'Power Off':2 -default 'Repeate' -center "$MSG"
    Xdialog --title "$1" --backtitle "$1" --ok-label 'Repeate' --cancel-label 'Power Off' --yesno "$2" 0 0
done
[ $Result -eq 1 ] && /sbin/poweroff
return $Result
}

MAX_TIMEOUT=30
MAX_COUNT=5
COUNTER=0
FLAG=1
while [ $FLAG -ne 0 ]; do
    START_TIME=$(date +%s)
    RDESKTOP_OUTPUT=`/usr/bin/rdesktop -f $RDP_OPTS $RDP_SERVER 2>&1 | grep '^ERROR:'`
    FINISH_TIME=$(date +%s)
    TIMEOUT=$((FINISH_TIME-START_TIME))
    if [ $TIMEOUT -le $MAX_TIMEOUT ]; then
	if [ $COUNTER -ge $MAX_COUNT ]; then
	    COUNTER=0
	    Message rdesktop "$RDESKTOP_OUTPUT" || FLAG=0
	else
	    COUNTER=$((COUNTER+1))
	fi
    else
	COUNTER=0
    fi
done
